#include <http/HttpHelper.h>
#include <openssl/SSLSocket.h>

#define HTTP_TEST_MAIN() int main(int argc, char** argv){return CommonMainProcess(argc, argv);}
#define HTTP_TEST_LOOP(__TIMES__) int main(int argc, char** argv){return CommonMainProcess(argc, argv, __TIMES__);}

#define ColorPrint(__COLOR__, __FMT__, ...)		\
SetConsoleTextColor(__COLOR__);					\
printf(__FMT__, __VA_ARGS__);					\
SetConsoleTextColor(eWHITE);					\

/*链接地址*/
extern const char* URL;

/*生成请求报文*/
extern string GetMessage();

/*打印应答报文*/
extern void PrintResult(const string& msg);

static HttpRequest _request;

void SetMethod(E_HTTP_METHOD method)
{
	HttpRequest tmp = _request;

	tmp.init(_request.getPath(), method);

	std::swap(_request, tmp);
}

void SetCookie(const string& cookie)
{
	_request.setCookie(cookie);
}

void SetContentType(const string& contype)
{
	_request.setHeadValue("Content-Type", contype);
}

void SetHeader(const string& key, const string& val)
{
    _request.setHeadValue(key, val);
}

void SetParameter(const string& key, const string& val)
{
	_request.setParameter(key, val);
}

int CommonMainProcess(int argc, char** argv)
{
	Process::Instance(argc, argv);

	int port;
	string ip;
	string host;
	string path;
	bool crypted;
	string msg = GetMessage();

	HttpRequest::GetInfoFromURL(URL, host, path, ip, port, crypted);

	_request.init(path, _request.getMethod());

	if (msg.length() > 0)
	{
		_request.setPayload(msg);
	}

	_request.setHeadHost(ip, port);

	SetConsoleTextColor(eWHITE);

	sp<Socket> sock = crypted ? SSLSocketPool::Connect(ip, port) : SocketPool::Connect(ip, port);

	if (!sock)
	{
		ColorPrint(eRED, "连接服务器[%s:%d]失败\n", ip.c_str(), port);

        return XG_NETERR;
	}

	_request.setHeadHost(host, port);

	SmartBuffer buffer = _request.getResult(sock);

	if (buffer.isNull())
	{
		ColorPrint(eRED, "%s\n", "接收应答消息失败");

		return XG_NETERR;
	}

	PrintResult(stdx::replace(buffer.str(), "\r", ""));

	return XG_OK;
}

int CommonMainProcess(int argc, char** argv, int times)
{
	while (times-- > 0) CommonMainProcess(argc, argv);

	return times;
}